package com.ftwj.demo.config.task;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import com.ftwj.demo.utils.logs.LoggerUtil;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
*
* <p>Title: ScheduleConfig</p>  
* <p>Description: 定义定时任务线程池</p>
* <p>Copyright: Copyright (c) 2020 </p>  
* <p>Company: 兰州飞天网景信息产业有限公司</p>    
* @author WangSLi
* @date 2020年2月28日 上午9:21:06
* @version V1.0
 */
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        //taskRegistrar.setScheduler(taskExecutor());
        //任务执行线程
        Runnable runnable = () -> LoggerUtil.info("EXECUTE TASK {}", 1);

        //任务触发器
        Trigger trigger = triggerContext -> {
            //获取定时触发器，这里可以每次从数据库获取最新记录，更新触发器，实现定时间隔的动态调整
            CronTrigger cronTrigger = new CronTrigger("0/2 * * * * ?");
            return cronTrigger.nextExecutionTime(triggerContext);
        };
        
        /*
        Trigger trigger = triggerContext -> {
            //获取定时触发器，这里可以每次从数据库获取最新记录，更新触发器，实现定时间隔的动态调整
            PeriodicTrigger periodicTrigger = new PeriodicTrigger(2000);
            return periodicTrigger.nextExecutionTime(triggerContext);
        };
        */
        
        //注册任务
        //taskRegistrar.addTriggerTask(runnable, trigger);
        //taskRegistrar.addTriggerTask(runnable, trigger);

    }

    @Bean
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(2<<3); //指定线程池大小
    }
}
